package com.zzw.springboot.service.impl;


import com.zzw.springboot.bean.Purchase;
import com.zzw.springboot.bean.PurchaseItem;
import com.zzw.springboot.mapper.PurchaseItemMapper;
import com.zzw.springboot.mapper.PurchaseMapper;
import com.zzw.springboot.service.InventoryService;
import com.zzw.springboot.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 采购单服务实现类
 */
@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private PurchaseItemMapper purchaseItemMapper;

    @Autowired
    private InventoryService inventoryService;

    @Override
    @Transactional
    public int addPurchase(Purchase purchase) {
        // 设置初始状态为草稿
        if (purchase.getStatus() == null) {
            purchase.setStatus(0);
        }

        // 如果没有传入采购单号，则自动生成
        if (purchase.getPurchaseNo() == null || purchase.getPurchaseNo().isEmpty()) {
            purchase.setPurchaseNo(generatePurchaseNo());
        }

        // 计算总金额
        if (purchase.getItems() != null && !purchase.getItems().isEmpty()) {
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (PurchaseItem item : purchase.getItems()) {
                // 计算明细金额 = 数量 * 单价
                BigDecimal amount = item.getUnitPrice().multiply(new BigDecimal(item.getQuantity()));
                item.setAmount(amount);
                totalAmount = totalAmount.add(amount);

                // 初始化已入库数量为0
                item.setReceivedQuantity(0);
            }
            purchase.setTotalAmount(totalAmount);
        }

        // 插入采购单
        int rows = purchaseMapper.insertPurchase(purchase);
        if (rows > 0 && purchase.getItems() != null && !purchase.getItems().isEmpty()) {
            // 插入采购单明细
            for (PurchaseItem item : purchase.getItems()) {
                item.setPurchaseId(purchase.getPurchaseId());
            }
            purchaseItemMapper.insertPurchaseItems(purchase.getItems());
        }

        return rows;
    }

    @Override
    @Transactional
    public int updatePurchase(Purchase purchase) {
        // 查询原采购单
        Purchase original = purchaseMapper.selectPurchaseById(purchase.getPurchaseId());
        if (original == null) {
            return 0;
        }

        // 只有草稿状态的采购单才能修改
        if (original.getStatus() != 0) {
            return 0;
        }

        // 更新采购单基本信息
        int rows = purchaseMapper.updatePurchase(purchase);

        // 更新采购单明细
        if (rows > 0 && purchase.getItems() != null && !purchase.getItems().isEmpty()) {
            // 先删除原明细
            purchaseItemMapper.deletePurchaseItemByPurchaseId(purchase.getPurchaseId());

            // 计算总金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (PurchaseItem item : purchase.getItems()) {
                // 计算明细金额 = 数量 * 单价
                BigDecimal amount = item.getUnitPrice().multiply(new BigDecimal(item.getQuantity()));
                item.setAmount(amount);
                totalAmount = totalAmount.add(amount);

                // 设置采购单ID
                item.setPurchaseId(purchase.getPurchaseId());

                // 初始化已入库数量为0
                item.setReceivedQuantity(0);
            }

            // 重新插入明细
            purchaseItemMapper.insertPurchaseItems(purchase.getItems());

            // 更新总金额
            purchase.setTotalAmount(totalAmount);
            purchaseMapper.updatePurchase(purchase);
        }

        return rows;
    }

    @Override
    @Transactional
    public int deletePurchase(Integer purchaseId) {
        // 查询原采购单
        Purchase original = purchaseMapper.selectPurchaseById(purchaseId);
        if (original == null) {
            return 0;
        }

        // 只有草稿状态的采购单才能删除
        if (original.getStatus() != 0) {
            return 0;
        }

        // 先删除明细
        purchaseItemMapper.deletePurchaseItemByPurchaseId(purchaseId);

        // 删除采购单
        return purchaseMapper.deletePurchase(purchaseId);
    }

    @Override
    @Transactional
    public int deletePurchaseBatch(Integer[] purchaseIds) {
        // 先删除明细
        purchaseItemMapper.deletePurchaseItemByPurchaseIds(purchaseIds);

        // 删除采购单
        return purchaseMapper.deletePurchaseBatch(purchaseIds);
    }

    @Override
    public Purchase getPurchaseById(Integer purchaseId) {
        // 查询采购单基本信息
        Purchase purchase = purchaseMapper.selectPurchaseById(purchaseId);
        if (purchase != null) {
            // 查询明细
            List<PurchaseItem> items = purchaseItemMapper.selectPurchaseItemsByPurchaseId(purchaseId);
            purchase.setItems(items);
        }
        return purchase;
    }

    @Override
    public List<Purchase> getPurchaseList(Purchase purchase) {
        return purchaseMapper.selectPurchaseList(purchase);
    }

    @Override
    @Transactional
    public int approvePurchase(Integer purchaseId, Integer approvalUserId, Integer status) {
        // 查询原采购单
        Purchase original = purchaseMapper.selectPurchaseById(purchaseId);
        if (original == null) {
            return 0;
        }

        // 只有审核中状态的采购单才能审批
        if (original.getStatus() != 1) {
            return 0;
        }

        // 更新审批信息
        return purchaseMapper.updatePurchaseApproval(purchaseId, approvalUserId, status);
    }

    @Override
    @Transactional
    public int cancelPurchase(Integer purchaseId) {
        // 查询原采购单
        Purchase original = purchaseMapper.selectPurchaseById(purchaseId);
        if (original == null) {
            return 0;
        }

        // 已入库和已完成的采购单不能取消
        if (original.getStatus() == 3 || original.getStatus() == 4) {
            return 0;
        }

        // 更新状态为已取消
        return purchaseMapper.updatePurchaseStatus(purchaseId, -1);
    }

    @Override
    @Transactional
    public int receiveItems(Integer purchaseId, Integer userId, List<PurchaseItem> items) {
        // 查询原采购单
        Purchase original = purchaseMapper.selectPurchaseById(purchaseId);
        if (original == null) {
            return 0;
        }

        // 只有已审核状态的采购单才能入库
        if (original.getStatus() != 2) {
            return 0;
        }

        boolean allReceived = true;
        int result = 0;

        // 更新已入库数量，并处理库存入库
        for (PurchaseItem item : items) {
            // 查询原明细
            PurchaseItem originalItem = purchaseItemMapper.selectPurchaseItemById(item.getItemId());
            if (originalItem == null || !originalItem.getPurchaseId().equals(purchaseId)) {
                continue;
            }

            // 计算新的已入库数量
            int receiveQuantity = item.getQuantity(); // 本次入库数量
            int newReceivedQty = originalItem.getReceivedQuantity() + receiveQuantity;

            // 已入库数量不能超过采购数量
            if (newReceivedQty > originalItem.getQuantity()) {
                newReceivedQty = originalItem.getQuantity();
                receiveQuantity = originalItem.getQuantity() - originalItem.getReceivedQuantity();
            }

            // 更新已入库数量
            result = purchaseItemMapper.updateReceivedQuantity(item.getItemId(), newReceivedQty);

            // 入库到库存系统
            if (result > 0 && receiveQuantity > 0) {
                // 假设默认入到ID为1的仓库，实际项目中应该从前端传入
                Integer warehouseId = 1;

                // 构建入库备注信息
                String remark = "采购入库：" + original.getPurchaseNo() + "-" + originalItem.getProductName();

                // 调用库存服务执行入库操作
                inventoryService.stockIn(
                    originalItem.getProductId(),
                    warehouseId,
                    receiveQuantity,
                    userId,
                    purchaseId,
                    1, // 1-采购单
                    remark
                );
            }

            // 如果有任何一个明细未完全入库，则标记为未全部入库
            if (newReceivedQty < originalItem.getQuantity()) {
                allReceived = false;
            }
        }

        // 更新采购单状态
        int newStatus = allReceived ? 4 : 3; // 4-已完成，3-已入库
        return purchaseMapper.updatePurchaseStatus(purchaseId, newStatus);
    }

    @Override
    public List<PurchaseItem> getPurchaseItemsByPurchaseId(Integer purchaseId) {
        return purchaseItemMapper.selectPurchaseItemsByPurchaseId(purchaseId);
    }

    @Override
    public String generatePurchaseNo() {
        // 生成采购单号，格式：PO + 年月日 + 3位流水号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String prefix = "PO" + sdf.format(new Date());

        // 查询当天最大单号
        return purchaseMapper.generatePurchaseNo(prefix);
    }
}
